//
//  ZZUILabel.swift
//  MeunDemo
//
//  Created by hfzhangzhang on 2018/3/19.
//  Copyright © 2018年 hfzhangzhang. All rights reserved.
//

import UIKit

public enum UICustomMeunItemOptions:Int {
    case UICustomMeunItem_copy
    case UICustomMeunItem_cut
    case UICustomMeunItem_paste
    case UICustomMeunItem_unSelect
}

class ZZMeunLabel: UILabel {

    var customMeunItemOptions:[UICustomMeunItemOptions] = [.UICustomMeunItem_copy,.UICustomMeunItem_unSelect]
    fileprivate var  oldBackgroundColor :UIColor?
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setUp()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUp()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    func setUp(){
        self.isUserInteractionEnabled = true
        oldBackgroundColor = self.backgroundColor;
        self.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPress)))
        NotificationCenter.default.addObserver(self, selector: #selector(menuControllerWillHide), name: NSNotification.Name.UIMenuControllerWillHideMenu, object: nil)
        
    }
    @objc func menuControllerWillHide(){
        self.resignFirstResponder()
        self.backgroundColor = oldBackgroundColor
    }
    @objc func longPress(){
        self.becomeFirstResponder()
        self.backgroundColor = UIColor.gray.withAlphaComponent(0.2)
        
        let menu = UIMenuController.shared
        menu.arrowDirection = UIMenuControllerArrowDirection.down
        if menu.isMenuVisible {
            return
        }
        let item1 = UIMenuItem.init(title: "复制", action:#selector(customCopy))
        let item2 = UIMenuItem.init(title: "取消", action:#selector(unSelect))
        menu.menuItems = [item1,item2];
        menu.setTargetRect(self.bounds, in: self)
        menu.setMenuVisible(true, animated: true)
        
    }
    override var canBecomeFirstResponder: Bool {
        return true;
    }
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        //if [#selector(test1), #selector(test2)].contains(action) {
        if (self.customMeunItemOptions.contains(.UICustomMeunItem_copy)&&action==#selector(customCopy)){
            return true;
        }
        if (self.customMeunItemOptions.contains(.UICustomMeunItem_unSelect)&&action==#selector(unSelect)){
            return true
        }
        return false;
        
    }
    
    @objc func customCopy(menu:UIMenuController) -> () {
        if let str = self.text {
            UIPasteboard.general.string = str;
        }
        
    }
    @objc func unSelect(UIMenuController:UIMenuController) -> () {
        return
    }
    deinit{
        self.resignFirstResponder()
       NotificationCenter.default.removeObserver(self)
    }

}

class SelectCopyLable: UITextView {
    
    
    
}











